package com.lei.yohuo001java;

import androidx.recyclerview.widget.LinearLayoutManager;
import androidx.recyclerview.widget.RecyclerView;

import android.annotation.SuppressLint;
import android.database.sqlite.SQLiteDatabase;
import android.os.Handler;
import android.os.Message;
import android.text.TextUtils;
import android.util.Log;
import android.view.View;
import android.widget.Button;
import android.widget.CheckBox;
import android.widget.TextView;
import android.widget.Toast;

import com.alipay.sdk.app.PayTask;
import com.chad.library.adapter.base.BaseQuickAdapter;
import com.dao.green.db.DaoMaster;
import com.dao.green.db.DaoSession;
import com.lei.mvp_retrofitlibrary.mvp.view.BaseActivity;
import com.lei.yohuo001java.adapter.MyCarAdapter;
import com.lei.yohuo001java.bean.GoodsEntiy;
import com.lei.yohuo001java.sandbox.PayResult;
import com.lei.yohuo001java.sandbox.util.OrderInfoUtil2_0;

import java.text.DecimalFormat;
import java.util.ArrayList;
import java.util.List;
import java.util.Map;

public class CarActivity extends BaseActivity {
    private RecyclerView actCarRv1;
    private CheckBox actCarRb;
    private TextView actCarTv2;
    private Button actCarBtJs;
    private List<GoodsEntiy> list = new ArrayList<>();
    private MyCarAdapter adapter;
    private int sum=0;
    private DaoSession daoSession;

    @Override
    public int bindlayout() {
        return R.layout.activity_car;
    }

    @Override
    public void initView() {
        actCarRv1 = (RecyclerView) findViewById(R.id.act_car_rv1);
        actCarRb = (CheckBox) findViewById(R.id.act_car_rb);
        actCarTv2 = (TextView) findViewById(R.id.act_car_tv2);
        actCarBtJs = (Button) findViewById(R.id.act_car_bt_js);
        getSql();
    }

    @Override
    public void initData() {
        adapter = new MyCarAdapter(R.layout.item_car_layout,list);
        actCarRv1.setAdapter(adapter);
        actCarRv1.setLayoutManager(new LinearLayoutManager(this));
        getMoney();
        adapter.setOnItemChildClickListener(new BaseQuickAdapter.OnItemChildClickListener() {
            @Override
            public void onItemChildClick(BaseQuickAdapter adapter, View view, int position) {
                CheckBox cb = view.findViewById(R.id.item_car_cb);
                switch (view.getId()){
                    case R.id.item_car_cb://多选
                        sum=0;
                        list.get(position).setSelect(cb.isChecked());
                        for (int i = 0; i < list.size(); i++) {
                            if (list.get(i).getSelect()){
                                ++sum;
                            }
                        }
                        if (sum==list.size()){
                            actCarRb.setChecked(true);
                        }else {
                            actCarRb.setChecked(false);
                        }
                        getMoney();
                        adapter.notifyDataSetChanged();
                        break;
                    case R.id.item_car_bt1://减
                        int select_num = (int) list.get(position).getSelect_num();
                        if (select_num>0){
                            list.get(position).setSelect_num(--select_num);
                            if (select_num<=0){
                                daoSession.delete(list.get(position));
                                list.remove(position);
                                adapter.notifyDataSetChanged();
                            }else {
                                GoodsEntiy goodsEntiy = new GoodsEntiy(list.get(position).getId(),
                                        list.get(position).getPicturl(),
                                        list.get(position).getTitle(),
                                        list.get(position).getPrice(),
                                        select_num,
                                        list.get(position).getSelect());
                                daoSession.update(goodsEntiy);
                            }
                        }
                        getMoney();
                        adapter.notifyDataSetChanged();
                        break;
                    case R.id.item_car_bt2://加
                        int select_num1 = (int) list.get(position).getSelect_num();
                        if (select_num1<100){
                            list.get(position).setSelect_num(++select_num1);
                            GoodsEntiy goodsEntiy = new GoodsEntiy(list.get(position).getId(),
                                    list.get(position).getPicturl(),
                                    list.get(position).getTitle(),
                                    list.get(position).getPrice(),
                                    select_num1,
                                    list.get(position).getSelect());
                            daoSession.update(goodsEntiy);
                        }
                        getMoney();
                        adapter.notifyDataSetChanged();
                        break;
                }
            }
        });
        actCarRb.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                for (GoodsEntiy goodsEntiy:list
                ) {
                    goodsEntiy.setSelect(actCarRb.isChecked());
                }
                getMoney();
                adapter.notifyDataSetChanged();
            }
        });
        actCarBtJs.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                String trim = actCarTv2.getText().toString().trim();
                if (!trim.equals("0.00")){
                    payV2(trim,"想买的");
                }else {
                    Toast.makeText(CarActivity.this, "请先选择商品", Toast.LENGTH_SHORT).show();
                }
            }
        });
    }

    private void getSql() {
        DaoMaster.DevOpenHelper goods_sql = new DaoMaster.DevOpenHelper(this, "goods_sql");
        SQLiteDatabase writableDatabase = goods_sql.getWritableDatabase();
        DaoMaster daoMaster = new DaoMaster(writableDatabase);
        daoSession = daoMaster.newSession();
        List<GoodsEntiy> goodsEntiys = daoSession.loadAll(GoodsEntiy.class);
        Log.e("ljl", "getSql: "+goodsEntiys.toString() );
        list.addAll(goodsEntiys);
    }

    private void getMoney(){
        double money = 0;
        for (int i = 0; i < list.size(); i++) {
            if (list.get(i).getSelect()){
                money+=list.get(i).getSelect_num()*list.get(i).getPrice();
            }
        }
        String format = new DecimalFormat("0.00").format(money);
        actCarTv2.setText(format+"");
    }


    /**
     * 支付宝
     */

    /**
     * 用于支付宝支付业务的入参 app_id。
     */
    public static final String APPID = "2016102700769935";

    /**
     * 用于支付宝账户登录授权业务的入参 pid。
     */
    public static final String PID = "";

    /**
     * 用于支付宝账户登录授权业务的入参 target_id。
     */
    public static final String TARGET_ID = "";

    /**
     *  pkcs8 格式的商户私钥。
     *
     * 	如下私钥，RSA2_PRIVATE 或者 RSA_PRIVATE 只需要填入一个，如果两个都设置了，本 Demo 将优先
     * 	使用 RSA2_PRIVATE。RSA2_PRIVATE 可以保证商户交易在更加安全的环境下进行，建议商户使用
     * 	RSA2_PRIVATE。
     *
     * 	建议使用支付宝提供的公私钥生成工具生成和获取 RSA2_PRIVATE。
     * 	工具地址：https://doc.open.alipay.com/docs/doc.htm?treeId=291&articleId=106097&docType=1
     */
    public static final String RSA2_PRIVATE = "MIIEvAIBADANBgkqhkiG9w0BAQEFAASCBKYwggSiAgEAAoIBAQCGgbycKrk+qenrIqL5ttDII+BPZcVY8YQlF7pSxsxAVn+QpmzMp5+5xfaIanzmfN4gyzTAlWOLFYtVmobUZd+Ul6017/is7gMY6hb0efk4A7nMVsTj0ExAV7+7mVKqe/KBQuhhemvb6hBnbOIjsMI2qCS0EWCio0RNR8FpWIqk60+LU43YLjMn/O2m2Ducrw3eb2qoeGUW2mlGLKwP1TIzYTMZ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Nb3d/v0V+wjcVtos3xW6BmOnQJVTA4eNd7zemH3eflP8U6BNA3oDGbjiGbhTL/ITulgFBCNuLb0CkYxC3Rj73QeW/dyUrYd0kCgYAPf09KCzBt5NYxhI4TmMvmGymSObbz9PAGCvxOoX1uCIawDZw815l5efXfZioSCt0nosI8KCeHctSX+UR/1LskUvyoozJ7tMLnsRHI3vZR9TTUa8Qosie12wYhan3ICLh/snsDnohWTJT9fDmLQEp7fqbSc27klRGNTTsmYmT/Nw==";
    public static final String RSA_PRIVATE = "";

    private static final int SDK_PAY_FLAG = 1;
    private static final int SDK_AUTH_FLAG = 2;




    @SuppressLint("HandlerLeak")
    private Handler mHandler = new Handler() {
        @SuppressWarnings("unused")
        public void handleMessage(Message msg) {
            switch (msg.what) {
                case SDK_PAY_FLAG: {
                    @SuppressWarnings("unchecked")
                    PayResult payResult = new PayResult((Map<String, String>) msg.obj);
                    /**
                     * 对于支付结果，请商户依赖服务端的异步通知结果。同步通知结果，仅作为支付结束的通知。
                     */
                    String resultInfo = payResult.getResult();// 同步返回需要验证的信息
                    String resultStatus = payResult.getResultStatus();
                    // 判断resultStatus 为9000则代表支付成功
                    if (TextUtils.equals(resultStatus, "9000")) {
                        // 该笔订单是否真实支付成功，需要依赖服务端的异步通知。
                        Toast.makeText(CarActivity.this, "支付成功", Toast.LENGTH_SHORT).show();

                        //支付成功

                    } else {
                        // 该笔订单真实的支付结果，需要依赖服务端的异步通知。
                        Toast.makeText(CarActivity.this, "支付失败" + payResult, Toast.LENGTH_SHORT).show();
                    }
                    break;
                }
                default:
                    break;
            }
        };
    };



    /**
     * 支付宝支付业务示例
     */
    public void payV2(String money,String goodsname) {
        if (TextUtils.isEmpty(APPID) || (TextUtils.isEmpty(RSA2_PRIVATE) && TextUtils.isEmpty(RSA_PRIVATE))) {
            Toast.makeText(this, "注意参数", Toast.LENGTH_SHORT).show();
            return;
        }

        /*
         * 这里只是为了方便直接向商户展示支付宝的整个支付流程；所以Demo中加签过程直接放在客户端完成；
         * 真实App里，privateKey等数据严禁放在客户端，加签过程务必要放在服务端完成；
         * 防止商户私密数据泄露，造成不必要的资金损失，及面临各种安全风险；
         *
         * orderInfo 的获取必须来自服务端；
         */
        boolean rsa2 = (RSA2_PRIVATE.length() > 0);
        Map<String, String> params = OrderInfoUtil2_0.buildOrderParamMap(APPID, rsa2,money,goodsname);
        String orderParam = OrderInfoUtil2_0.buildOrderParam(params);

        String privateKey = rsa2 ? RSA2_PRIVATE : RSA_PRIVATE;
        String sign = OrderInfoUtil2_0.getSign(params, privateKey, rsa2);
        final String orderInfo = orderParam + "&" + sign;

        final Runnable payRunnable = new Runnable() {

            @Override
            public void run() {
                PayTask alipay = new PayTask(CarActivity.this);
                Map<String, String> result = alipay.payV2(orderInfo, true);
                Log.i("msp", result.toString());

                Message msg = new Message();
                msg.what = SDK_PAY_FLAG;
                msg.obj = result;
                mHandler.sendMessage(msg);
            }
        };

        // 必须异步调用
        Thread payThread = new Thread(payRunnable);
        payThread.start();
    }
}
